﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;

namespace net.xBei.WebApi.FrameworkExtensions {
    /// <inheritdoc/>
    public class TextPlainInputFormatter : TextInputFormatter {
        /// <inheritdoc/>
        public TextPlainInputFormatter() {
            SupportedMediaTypes.Add("text/plain");
            SupportedEncodings.Add(UTF8EncodingWithoutBOM);
            SupportedEncodings.Add(UTF16EncodingLittleEndian);
        }
        /// <inheritdoc/>
        protected override bool CanReadType(Type type) {
            return type == typeof(string);
        }
        /// <inheritdoc/>
        public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,
                                                                              Encoding encoding) {
            string data = string.Empty;
            using (var streamReader = context.ReaderFactory(
                context.HttpContext.Request.Body,
                encoding)) {
                data = await streamReader.ReadToEndAsync();
            }

            return InputFormatterResult.Success(data);
        }
    }
}
